package pt.ua.helpdesk.global;

import com.jscape.inet.email.EmailMessage;
import com.jscape.inet.smtpssl.SmtpSsl;

/**
 * Class that handles the general global methods.
 * This class is a singleton
 * @author Amigos do Noddy
 */
public class Global {
	private static Global instance;
	private static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
	private static final String PROTOCOL = "jdbc:derby:C:/Documentos/Universidade/work/helpdesk/hddb;";
	
	/**
	 * Construtor
	 */
	public Global(){}
	
	
	/**
	 * Gets the singleton instance
	 * @return Instancia
	 */
	public Global getInstance()
	{
		if(instance == null)
			return new Global();
		else
			return instance;
	}
	
	/**
	 * Get Driver
	 * @return Driver
	 */
	public static String getDRIVER()
	{
		return DRIVER;
	}
	
	/**
	 * Get Protocol
	 * @return Protocol
	 */
	public static String getPROTOCOL()
	{
		return PROTOCOL;
	}
	
	public static native void redirect(String url)/*-{
    	$wnd.location = url;
	}-*/;
	
	/**
	 * Sends an email
	 * 
	 * @param to Target address
	 * @param subject Subject
	 * @param body Body text
	 * @return True in the case of success
	 */
	public static boolean sendEmail(String to, String subject, String body)
	{
		SmtpSsl smtp = null;
	     
	     // gmail username - CHANGE THIS
	     String user = "aauav.helpdesk@gmail.com";
	     // gmail password - CHANGE THIS
	     String password = "associacao";
	     
	     try {      
		       // create a new SmtpSsl instance connecting securely via port 465 using implicit SSL
		       smtp = new SmtpSsl("smtp.gmail.com",465);
		       
		       // establish secure connection
		       smtp.connect();
		       
		       // login using gmail account details
		       smtp.login(user,password);
		       
		       // create new email message
		       EmailMessage message = new EmailMessage();
		       message.setContentType("text/html");
		       message.setTo(to);
		       message.setFrom(user);
		       message.setSubject(subject);
		       message.setBody(body);
		       
		       // send message
		       smtp.send(message);
		       
		       // disconnect      
		       smtp.disconnect();
		       return true;
	     } catch(Exception e) {
	    	 return false;
	     } 
	}
	
	/**
	 * Generates a random code.
	 * Mainly used for activation codes
	 * 
	 * @param min Minimum size
	 * @param max Maximum size
	 * @return Code
	 */
	public static long generateCode(int min, int max)
	{
		return (long) (Math.random() * (max - min + 1) ) + min;
	}
}
